import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:share_plus/share_plus.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:path/path.dart';
import 'dart:typed_data';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'diy.dart';
class DiyMePage extends StatefulWidget {
  const DiyMePage({
    super.key,
  });

  @override
  State<DiyMePage> createState() => _DiyMePageState();
}

class _DiyMePageState extends State<DiyMePage> {
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  List<Map<String, dynamic>> images = [];

  Future<Database> getDatabase() async {
    return openDatabase(
      join(await getDatabasesPath(), 'images.db'),
      onCreate: (db, version) {
        return db.execute(
          'CREATE TABLE images(id INTEGER PRIMARY KEY, image BLOB)',
        );
      },
      version: 1,
    );
  }

  Future<void> deleteImageById(int id) async {
    final db = await getDatabase();

    // 执行删除操作
    await db.delete(
      'images',
      where: 'id = ?',
      whereArgs: [id],
    );

    // print('已删除 id 为 $id 的项');
  }

  Future<void> loadImageFromDatabase() async {
    final db = await getDatabase();
    final List<Map<String, dynamic>> maps = await db.query('images');
    

    // if (maps.isNotEmpty) {
    //   setState(() {
    //     images = maps.map((map) => map['image'] as Uint8List).toList();
    //   });
    // }
    if (maps.isNotEmpty) {
      setState(() {
        // // maps = maps.toList();
        // images = maps.map((map) => map['image'] as Uint8List).toList();
        images = maps.map((map) {
        return {
          'id': map['id'], // 获取 id 属性
          'image': map['image'] as Uint8List // 获取 image 属性并转换为 Uint8List
        };
      }).toList();
      });
    }
  }

  Future<void> _logScreenView() async {
    await analytics.logScreenView(
      screenName: 'MineDIY Page ES',
      screenClass: 'MineDIYPage_ES',
    );
  }

  Future<void> shareImage(List<int> bytes) async {
    final tempDir = await getTemporaryDirectory();
    final tempFile = File('${tempDir.path}/shared_image.jpg');
    await tempFile.writeAsBytes(bytes);
    await Share.shareXFiles(
      [XFile(tempFile.path)],
      text: 'Esta es la tarjeta que diseñé para ti yo mismo. ¿Te gusta?',
      sharePositionOrigin: const Rect.fromLTWH(0, 0, 100, 100),
      subject: 'Compartiendo mi tarjeta hecha a mano',
      // chooserTitle: 'Share via',
    );
  }

  @override
  void initState() {
    super.initState();
    loadImageFromDatabase();
    _logScreenView();    
  }

  @override
  Widget build(BuildContext context) {
    return images.isEmpty ? Center(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            height: 128,
            child: Image.asset('images/empty.png'),
          ),
          const SizedBox(height: 24,),
          InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const DiyPage(),
                ),
              );
            },
            child: Container(
              width: 160,
              height: 48,
              decoration: BoxDecoration(
                color: const Color.fromARGB(255, 215, 31, 39),
                borderRadius: BorderRadius.circular(24),
              ),
              child: const Center(
                child: Text('DIY ahora', style: TextStyle(color: Colors.white, fontFamily: 'OpenSans', fontSize: 18),),
              ) ,
            ),
          )
          
        ],
      ),
    )  : SingleChildScrollView(
        child: Container(
          padding: const EdgeInsets.only(left: 8, right: 8, top: 16, bottom: 16),
          child: Wrap(
            spacing: 0, // 水平方向的间距
            runSpacing: 0, // 垂直方向的间距
            children: List.generate(images.length, (index) {
              return Stack(
                children: [
                 Container(
                    alignment: Alignment.bottomRight,
                    // padding: const EdgeInsets.only(top: 24,left: 8, right: 12),
                    width: (MediaQuery.of(context).size.width -16) / 2, // 每个Container的宽度
                    height: (MediaQuery.of(context).size.width-16) / 2, // Container的高度
                    
                    decoration: BoxDecoration(
                      // borderRadius: BorderRadius.circular(10),
                      image: DecorationImage(
                        image: MemoryImage(images[index]['image']),
                        fit: BoxFit.cover,

                      )
                    ),
                    
                  ),
                  Positioned(
                    left: 8,
                    right: 8,
                    bottom: 20,
                    child: Container(
                      // color: Colors.red,
                      child: Row(
                        // mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          InkWell(
                            onTap: () {
                              deleteImageById(images[index]['id']);
                              // print(images[index]['id']);
                              images.removeAt(index);
                              setState(() {
                                images = images;
                              });
                              // shareImage(images[index]);
                            },
                            child: Container(
                              width: 40,
                              height: 40,
                              decoration: const BoxDecoration(
                                color: Color.fromRGBO(0, 0, 0, .75),
                                borderRadius: BorderRadius.all(Radius.circular(4)),
                              ),
                              child: const Icon(CupertinoIcons.delete, color: Colors.white,),
                            ),
                          ),
                          const SizedBox(width: 12,),
                          InkWell(
                            onTap: () {
                              shareImage(images[index]['image']);
                            },
                            child: Container(
                              width: 40,
                              height: 40,
                              decoration: const BoxDecoration(
                                color: Color.fromRGBO(0, 0, 0, .75),
                                borderRadius: BorderRadius.all(Radius.circular(4)),
                              ),
                              child: const Icon(CupertinoIcons.share, color: Colors.white,),
                            ),
                          ),
                          const SizedBox(width: 12),
                          InkWell(
                            onTap: () async {
                              final result = await ImageGallerySaver.saveImage(images[index]['image']);
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('¡Guardado con éxito en la galería!', style: TextStyle(fontFamily: 'OpenSans', fontSize: 16),),
                                  duration: Duration(seconds: 2),
                                  backgroundColor: Colors.green,
                                ),
                              );
                              // _saved(images[index]);
                            },
                            child: Container(
                              width: 40,
                              height: 40,
                              decoration: const BoxDecoration(
                                color: Color.fromRGBO(0, 0, 0, .75),
                                borderRadius: BorderRadius.all(Radius.circular(4)),
                              ),
                              child: const Icon(CupertinoIcons.cloud_download, color: Colors.white,),
                            ),
                          )
                        ],
                      ),
                    ) ,
                  )
                  
                ],
              ) ;
            })
          ),
        ) ,
      );
  }

}